/**
 * Created by Freeman on 2016/6/27.
 */


var passport = require('passport');
var GithubStrategy = require('passport-github').Strategy;
var tools = require('../../util/tools');

exports.setup = function (User, settings) {
    passport.use(new GithubStrategy({
        clientID: settings.github.clientID,
        clientSecret: settings.github.clientSecret,
        callbackURL: settings.github.callbackURL,
        passReqToCallback: true
    }, function (req, accessToken, refreshToken, profile, done) {
        var userId = req.session.passport.userId || null;
        profile._json.token = accessToken;
        if (!userId) {
            User.findOne({
                'github.id': profile.id
            }, function (err, user) {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    //用户呢称需要唯一.
                    var newUser = {
                        nickname: profile.displayName || profile.username,
                        avatar: profile._json.avatar_url || '',
                        provider: 'github',
                        github: profile._json,
                        status: 1
                    };

                    User.findOne({
                        'nickname': newUser.nickname
                    }, function (err, user) {
                        if (err) return done(err);
                        if (user) {
                            newUser.nickname = tools.randomString();
                        }
                        user = new User(newUser);
                        user.save(function (err) {
                            if (err) return done(err);
                            done(err, user);
                        });
                    })
                } else {
                    return done(err, user);
                }
            })
        } else {
            //用户已经登录
            return done(new Error('您已经是登录状态了'));
        }
    }));
};

